#pragma once
#include <iostream>
#include <jsoncpp/json/json.h>
#include <sstream>
#include <memory>
bool serialize(const Json::Value& str, std::string& body)
{
    // 输出对象
    std::stringstream ss;
    // 建立工厂对象
    Json::StreamWriterBuilder val;
    // 实例化出派生对象
    std::unique_ptr<Json::StreamWriter> value(val.newStreamWriter());
    // 序列化
    int ret = value->write(str, &ss);
    if(ret != 0)
    {
        printf("serialize failed!\n");
        return false;
    }
    body = ss.str();
    return true;
}
bool unserialize(const std::string &body, Json::Value &val)
{
    // 实例化出工厂
    Json::CharReaderBuilder crb;
    std::string errs;
    //通过工厂类对象来生产派生类对象
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
    // 反序列化
    bool ret = cr->parse(body.c_str(), body.c_str() + body.size(), &val, &errs);
    if(ret == false)
    {
        std::cout << "json unserialize failed : " << errs << std::endl;
        return false;
    }
    return true;
}
void test_json()
{
    const char* name = "sss";
    int age = 22;
    const char* sex = "girl";
    float score[] = {11, 13, 13};
    Json::Value Student;
    Student["name"] = name;
    Student["age"] = age;
    Student["sex"] = sex;
    Student["score"].append(score[0]);
    Student["score"].append(score[1]);
    Student["score"].append(score[2]);
    Json::Value fan;
    fan["book"] = "西游记";
    fan["exercise"] = "foolball";
    Student["fan"] = fan;
    std::string ret;
    if(serialize(Student, ret))
    {
        std::cout << ret << std::endl;
    }
    std::string str = R"({"姓名":"小黑", "年龄": 19, "成绩":[32, 45, 56]})";
    Json::Value stu;
    bool rets = unserialize(str, stu);
    if (rets == false) 
        abort();
    std::cout << "姓名: " <<  stu["姓名"].asString() << std::endl;
    std::cout << "年龄: " <<  stu["年龄"].asInt() << std::endl;
    int sz = stu["成绩"].size();
    for (int i = 0; i < sz; i++) {
        std::cout << "成绩: " <<  stu["成绩"][i].asFloat() << std::endl;
    }
}